package com.asiainfo.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import com.asiainfo.bean.AuthorityBean;
import com.asiainfo.service.AuthorityService;

/**
 * 加载资源与权限对应关系
 * @author luhf
 * @date 2013-1-19 下午10:01:18
 */
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource{
	
	private static final Logger log=LoggerFactory.getLogger(MySecurityMetadataSource.class);

	private AuthorityService authorityService;
	public AuthorityService getAuthorityService(){
		return authorityService;
	}
	public void setAuthorityService(AuthorityService authorityService){
		this.authorityService=authorityService;
	}

	//加载所有资源与权限的关系
	private static Map<String,Collection<ConfigAttribute>> authorityMap=null;

	public MySecurityMetadataSource(AuthorityService authorityService){
		this.authorityService=authorityService;
		loadResourceDefine();
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes(){
		return null;
	}

	// 返回所请求资源所需要的权限
	@Override
	public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException{
		String requestUrl=((FilterInvocation)obj).getRequestUrl();
		log.debug("requestUrl is {} "+requestUrl);
		if(authorityMap==null){
			loadResourceDefine();
		}
		return authorityMap.get(requestUrl);
	}

	@Override
	public boolean supports(Class<?> arg0){
		return true;
	}
	
	/**
	 * 加载系统资源与权限列表
	 */
	private void loadResourceDefine(){
		if(authorityMap==null){
			authorityMap=new HashMap<String,Collection<ConfigAttribute>>();
			List<AuthorityBean> authorityBeans=authorityService.getAuthorityList();
			for(AuthorityBean authorityBean:authorityBeans){
				Collection<ConfigAttribute> configAttributes=new ArrayList<ConfigAttribute>();
				ConfigAttribute configAttribute=new SecurityConfig(authorityBean.getAuthName());
				configAttributes.add(configAttribute);
				authorityMap.put(authorityBean.getAuthURL(),configAttributes);
			}
		}

//		Set<Entry<String,Collection<ConfigAttribute>>> resourceSet=authorityMap.entrySet();
//		Iterator<Entry<String,Collection<ConfigAttribute>>> iterator=resourceSet.iterator();

	}

}
